﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

namespace Pan
{
    public partial class download : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string id = Request.QueryString["file"];
            if (id == "" || id == null)
            {
                Session["error"] = "文件找不到了";
                Response.StatusCode = 404;
                return;
            }
            SqlConnection conn = new SqlConnection();
            conn.ConnectionString = ConfigurationManager.ConnectionStrings["PanConnectionString"].ToString();
            try
            {
                conn.Open();
                SqlCommand cmdFile = new SqlCommand();
                cmdFile.Connection = conn;
                cmdFile.CommandType = CommandType.StoredProcedure;
                cmdFile.CommandText = "GetFileByCode";
                cmdFile.Parameters.Add("@code", SqlDbType.VarChar).Value = id;
                SqlDataReader sdr = cmdFile.ExecuteReader();
                if (sdr.Read())
                {
                    string fileName = sdr["name"].ToString();
                    string filePath = Server.MapPath("/Uploads/" + sdr["location"].ToString());
                    FileInfo fileInfo = new FileInfo(filePath);
                    if (fileInfo.Exists)
                    {
                        Response.Clear();
                        Response.ClearContent();
                        Response.ClearHeaders();
                        Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
                        Response.AddHeader("Content-Length", fileInfo.Length.ToString());
                        Response.AddHeader("Content-Transfer-Encoding", "binary");
                        Response.ContentType = "application/octet-stream";
                        Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
                        Response.WriteFile(fileInfo.FullName);
                        Response.Flush();
                        Response.End();
                        return;
                    }
                }
                Session["error"] = "文件找不到了";
                Response.StatusCode = 404;
            }
            catch (Exception err)
            {
                Response.Write(err.Message);
            }
            finally
            {
                conn.Close();
            }
        }
    }
}